package cn.wuxuan.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.wuxuan.po.User;
import cn.wuxuan.service.UserService;
import cn.wuxuan.service.Impl.UserServiceImpl;
import cn.wuxuan.vo.Msg;

import com.alibaba.fastjson.JSON;

@WebServlet("/login.oas")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	UserService service = new UserServiceImpl();
	String name =null;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
	req.setCharacterEncoding("utf-8");
	resp.setContentType("application/json;charset=utf-8");
	PrintWriter out = resp.getWriter();
	String cmd = req.getParameter("cmd");
	name = req.getParameter("name");
	if("checkName".equals(cmd)){
		Boolean hasName = false;
		User user = service.selectName(name);
		if(user!=null){
			hasName = true;
		}
		out.print(hasName);
		
	}else if("login".equals(cmd)){
		HttpSession  session = req.getSession();
		String rand = (String) session.getAttribute("rand");
		String name = req.getParameter("name");
		String pwd = req.getParameter("pwd");
		String verifyCode = req.getParameter("verifyCode");
		String msgJson = null;
		Msg msg = null;
		if(rand.equals(verifyCode)){
			User user = new User(name,pwd);
			Integer count = service.verifyUser(user);
			if(count==1){
			msg = new Msg(1,"登录成功");
			Cookie cookie = new Cookie("userName", name);
			resp.addCookie(cookie);
			}else{
				msg = new Msg(0,"密码错误");
			}
		}else {
		msg = new Msg(0,"验证码不正确");
		}
		msgJson = JSON.toJSONString(msg);
		out.print(msgJson);
	}
}
}
